import React, { Component } from "react";
import { Text, View, StyleSheet, TouchableOpacity, Platform, DeviceEventEmitter, Switch, FlatList, ScrollView } from 'react-native';
import Constant from '../../../utils/Constant'//全局变量
import Header from "../../../components/header";
const isAndroid = Platform.OS == 'android';
import RangeSlider from 'rn-range-slider';

let navigation = null

export default class SeekMoreFilterPage extends Component {
    constructor(props) {
        super(props);

        this.rangeSlider = React.createRef();
        this.rangeSliderAge = React.createRef();
        this.rangeSliderPrice = React.createRef();

        this.state = {
            mileShowText: '不限',
            mileageMin: 0,
            mileageMax: 10,
            ageShowText: '不限',
            registerDateBegin: 0,
            registerDateEnd: 8,

            priceText: '不限',
            carPriceMin: 0,
            carPriceMax: 60,

            outColors: [
                { colorTitle: '不限', colorId: false, color: '', selected: true }, { colorTitle: '银灰色', colorId: 1, color: '#c1c1c1', selected: false }
                , { colorTitle: '深灰色', colorId: 2, color: '#888888', selected: false }, { colorTitle: '黑色', colorId: 3, color: '#222222', selected: false }
                , { colorTitle: '白色', colorId: 4, color: '#ffffff', selected: false }, { colorTitle: '红色', colorId: 5, color: '#c83138', selected: false }
                , { colorTitle: '蓝色', colorId: 6, color: '#466cb3', selected: false }, { colorTitle: '咖啡色', colorId: 7, color: '#70462B', selected: false }
                , { colorTitle: '香槟色', colorId: 8, color: '#E0D0AF', selected: false }, { colorTitle: '黄色', colorId: 9, color: '#F5D94D', selected: false }
                , { colorTitle: '紫色', colorId: 10, color: '#783B6F', selected: false }, { colorTitle: '绿色', colorId: 11, color: '#9EC573', selected: false }
                , { colorTitle: '橙色', colorId: 12, color: '#e87b3b', selected: false }, { colorTitle: '棕色', colorId: 14, color: '#744124', selected: false },
                { colorTitle: '其他', colorId: 17, color: '', selected: false }],
            carOutColorListData: [],


            inColors: [
                { colorTitle: '不限', colorId: false, color: '', selected: true }, { colorTitle: '银灰色', colorId: 1, color: '#c1c1c1', selected: false }
                , { colorTitle: '深灰色', colorId: 2, color: '#888888', selected: false }, { colorTitle: '黑色', colorId: 3, color: '#222222', selected: false }
                , { colorTitle: '白色', colorId: 4, color: '#ffffff', selected: false }, { colorTitle: '红色', colorId: 5, color: '#c83138', selected: false }
                , { colorTitle: '蓝色', colorId: 6, color: '#466cb3', selected: false }, { colorTitle: '咖啡色', colorId: 7, color: '#70462B', selected: false }
                , { colorTitle: '香槟色', colorId: 8, color: '#E0D0AF', selected: false }, { colorTitle: '黄色', colorId: 9, color: '#F5D94D', selected: false }
                , { colorTitle: '紫色', colorId: 10, color: '#783B6F', selected: false }, { colorTitle: '绿色', colorId: 11, color: '#9EC573', selected: false }
                , { colorTitle: '橙色', colorId: 12, color: '#e87b3b', selected: false }, { colorTitle: '棕色', colorId: 14, color: '#744124', selected: false },
                { colorTitle: '其他', colorId: 17, color: '', selected: false }],
            carInColorListData: [],

        };
    }

    componentDidMount() {
        navigation = this.props.navigation;
        this.initData()
    }

    initData() {
        if (this.props.route && this.props.route.params) {
            let params = this.props.route.params;
            console.log('params =====', params)

            if (this.rangeSlider.current) {
                const lowValue = params.mileageMin ? params.mileageMin : 0;
                const highValue = params.mileageMax ? params.mileageMax : 10;
                this.rangeSlider.current.setLowValue(lowValue);
                this.rangeSlider.current.setHighValue(highValue);
            }

            if (this.rangeSliderAge.current) {
                const lowValue = params.registerDateBegin ? params.registerDateBegin : 0;
                const highValue = params.registerDateEnd ? params.registerDateEnd : 8;
                this.rangeSliderAge.current.setLowValue(lowValue);
                this.rangeSliderAge.current.setHighValue(highValue);
            }

            if (this.rangeSliderPrice.current) {
                const lowValue = params.carPriceMin ? params.carPriceMin : 0;
                const highValue = params.carPriceMax ? params.carPriceMax : 60;
                this.rangeSliderPrice.current.setLowValue(lowValue);
                this.rangeSliderPrice.current.setHighValue(highValue);
            }

            // 选中颜色
            if(params.carOutColor && params.carOutColor.length > 0){
                this.setState({
                    carOutColorListData: params.carOutColor
                })
                params.carOutColor.forEach((item, index) => {
                    this.state.outColors.map((color, index) => {
                        if(color.colorTitle == '不限'){
                            color.selected = false;
                        }
                        if (color.colorTitle == item) {
                            color.selected = true;
                        }
                    })
                })
            }

            // 选中外观颜色
            if(params.carInColor && params.carInColor.length > 0){
                this.setState({
                    carInColorListData: params.carInColor
                })
                params.carOutColor.forEach((item, index) => {
                    this.state.inColors.map((color, index) => {
                        if(color.colorTitle == '不限'){
                            color.selected = false;
                        }
                        if (color.colorTitle == item) {
                            color.selected = true;
                        }
                    })
                })
            }

        }
    }

    render() {
        return (
            <View style={styles.container}>
                <Header navigation={navigation} Title={'更多'} ></Header>

                <ScrollView style={{ flex: 1 }}>

                    <View style={styles.mileContain}>
                        <View style={styles.mileTitleContain}>
                            <Text style={styles.titleText}>里程（万公里）</Text>
                            <Text style={styles.mileValueText}>{this.state.mileShowText}</Text>
                        </View>

                        <RangeSlider
                            ref={this.rangeSlider}
                            style={{ width: '100%', height: 60 }}
                            gravity={'center'}
                            min={0}
                            max={10}
                            step={1}
                            selectionColor="#ffdb1b"
                            blankColor="#e4e4e4"
                            labelStyle={'none'}
                            onValueChanged={(low, high, fromUser) => {
                                this.changeMile(low, high)
                            }}
                            thumbBorderWidth={4}
                            thumbBorderColor={'#fff'}
                            thumbColor={'#ffdb1b'}
                        />
                        <View style={styles.rangeTipContain}>
                            <Text>0</Text>
                            <Text>5</Text>
                            <Text>不限</Text>
                        </View>

                    </View>

                    <View style={styles.mileContain}>
                        <View style={styles.mileTitleContain}>
                            <Text style={styles.titleText}>车龄（年）</Text>
                            <Text style={styles.mileValueText}>{this.state.ageShowText}</Text>
                        </View>

                        <RangeSlider
                            ref={this.rangeSliderAge}
                            style={{ width: '100%', height: 60 }}
                            gravity={'center'}
                            min={0}
                            max={8}
                            step={1}
                            selectionColor="#ffdb1b"
                            blankColor="#e4e4e4"
                            labelStyle={'none'}
                            onValueChanged={(low, high, fromUser) => {
                                this.changeAge(low, high)
                            }}
                            thumbBorderWidth={4}
                            thumbBorderColor={'#fff'}
                            thumbColor={'#ffdb1b'}
                        />
                        <View style={styles.rangeTipContain}>
                            <Text>0</Text>
                            <Text>4</Text>
                            <Text>不限</Text>
                        </View>

                    </View>


                    {/* 价格筛选组件 */}
                    <View style={styles.mileContain}>
                        <View style={styles.mileTitleContain}>
                            <Text style={styles.titleText}>价格（万元）</Text>
                            <Text style={styles.mileValueText}>{this.state.priceText}</Text>
                        </View>

                        <RangeSlider
                            ref={this.rangeSliderPrice}
                            style={{ width: '100%', height: 60 }}
                            gravity={'center'}
                            min={0}
                            max={60}
                            step={1}
                            selectionColor="#ffdb1b"
                            blankColor="#e4e4e4"
                            labelStyle={'none'}
                            onValueChanged={(low, high, fromUser) => {
                                this.changePrice(low, high)
                            }}
                            thumbBorderWidth={4}
                            thumbBorderColor={'#fff'}
                            thumbColor={'#ffdb1b'}
                        />

                        <View style={styles.rangeTipContain}>
                            <Text>0</Text>
                            <Text>10</Text>
                            <Text>20</Text>
                            <Text>30</Text>
                            <Text>40</Text>
                            <Text>50</Text>
                            <Text>不限</Text>
                        </View>

                    </View>


                    <View style={[styles.mileContain, { paddingBottom: 10 }]}>
                        <View style={styles.mileTitleContain}>
                            <Text style={styles.titleText}>外观颜色</Text>
                        </View>
                        <FlatList
                            data={this.state.outColors}
                            renderItem={({ item, index }) => this.renderColorItem(item, index)}
                            keyExtractor={(item, index) => index}
                            extraData={this.state}
                            numColumns={4} />
                    </View>

                    <View style={[styles.mileContain, { paddingBottom: 10 }]}>
                        <View style={styles.mileTitleContain}>
                            <Text style={styles.titleText}>内饰颜色</Text>
                        </View>
                        <FlatList
                            data={this.state.inColors}
                            renderItem={({ item, index }) => this.renderInColorItem(item, index)}
                            keyExtractor={(item, index) => index}
                            extraData={this.state}
                            numColumns={4} />
                    </View>

                </ScrollView>

                <View style={[styles.bottomTabContainer, { height: 50 + Constant.bottomHeight }]}>
                    <TouchableOpacity
                        style={styles.resetBtn}
                        onPress={() => { this.resetFilter() }}>
                        <Text style={styles.btnText}>重置</Text>
                    </TouchableOpacity>
                    <TouchableOpacity
                        style={styles.confirmBtn}
                        onPress={() => { this.confirmFilter() }}>
                        <Text style={styles.btnText}>确认</Text>
                    </TouchableOpacity>
                </View>

            </View>
        )
    }

    renderColorItem(item, index) {
        return (
            <TouchableOpacity
                key={index}
                style={item.selected ? styles.colorSelectItem : styles.colorItem}
                activeOpacity={0.8}
                onPress={() => {
                    this.changeColor(index)
                }}>
                {item.color != '' ?
                    <View style={[styles.colorBox, { backgroundColor: item.color, borderWidth: 1, borderColor: item.colorTitle == '白色' ? '#e4e4e4' : '#fff' }]}></View>
                    : null}

                <Text style={styles.colorText}>{item.colorTitle}</Text>
            </TouchableOpacity>
        )
    }

    renderInColorItem(item, index) {
        return (
            <TouchableOpacity
                key={index}
                style={item.selected ? styles.colorSelectItem : styles.colorItem}
                activeOpacity={0.8}
                onPress={() => {
                    this.changeInColor(index)
                }}>
                {item.color != '' ?
                    <View style={[styles.colorBox, { backgroundColor: item.color, borderWidth: 1, borderColor: item.colorTitle == '白色' ? '#e4e4e4' : '#fff' }]}></View>
                    : null}

                <Text style={styles.colorText}>{item.colorTitle}</Text>
            </TouchableOpacity>
        )
    }

    changeColor(index) {
        let newCarOutColorData = []
        const selectedColor = this.state.outColors[index];

        // 如果选项为不限，清除其他选项
        if (selectedColor.colorTitle === '不限') {
            newCarOutColorData = []
            this.state.outColors.forEach((item, idx) => {
                if (item.colorTitle === '不限') {
                    item.selected = true
                }else {
                    item.selected = false
                }
            })
        }else {
            this.state.outColors[index].selected = !this.state.outColors[index].selected
            this.state.outColors.forEach((item, idx) => {
                if (item.colorTitle === '不限') {
                    item.selected = false
                }else{
                    if(item.selected){
                        newCarOutColorData.push(item.colorTitle)
                    }
                }
            })
        }
        console.log('newCarOutColorData', newCarOutColorData)
        this.setState({
            carOutColorListData: newCarOutColorData,
        })
    }

    changeInColor(index) {
        let newCarInColorData = []
        const selectedColor = this.state.inColors[index];

        // 如果选项为不限，清除其他选项
        if (selectedColor.colorTitle === '不限') {
            newCarInColorData = []
            this.state.inColors.forEach((item, idx) => {
                if (item.colorTitle === '不限') {
                    item.selected = true
                }else {
                    item.selected = false
                }
            })
        }else {
            this.state.inColors[index].selected = !this.state.inColors[index].selected
            this.state.inColors.forEach((item, idx) => {
                if (item.colorTitle === '不限') {
                    item.selected = false
                }else{
                    if(item.selected){
                        newCarInColorData.push(item.colorTitle)
                    }
                }
            })
        }
        console.log('newCarInColorData', newCarInColorData)
        this.setState({
            carInColorListData: newCarInColorData,
        })
    }

    changeMile(leftValue, rightValue) {
        let mileText = ''
        if (leftValue == 0 && rightValue == 10) {
            mileText = '不限'
        } else if (leftValue == 0) {
            mileText = rightValue + "万公里以下"

        } else if (leftValue >= 1 && rightValue == 10) {
            mileText = leftValue + "万公里以上"

        } else if (leftValue >= 1) {
            mileText = leftValue + "-" + rightValue + "万公里"

        }
        if(leftValue  == 0){
            leftValue = null
        }
        if(rightValue  == 10){
            rightValue = null
        }

        this.setState({
            mileShowText: mileText,
            mileageMin: leftValue,
            mileageMax: rightValue
        })
    }

    changeAge(leftValue, rightValue) {
        let mileText = ''
        if (leftValue == 0 && rightValue == 8) {
            mileText = '不限'
        } else if (leftValue == 0) {
            mileText = rightValue + "年以下"

        } else if (leftValue >= 1 && rightValue == 8) {
            mileText = leftValue + "年以上"

        } else if (leftValue >= 1) {
            mileText = leftValue + "-" + rightValue + "年"

        }

        if(leftValue  == 0){
            leftValue = null
        }
        if(rightValue  == 8){
            rightValue = null
        }

        this.setState({
            ageShowText: mileText,
            registerDateBegin: leftValue,
            registerDateEnd: rightValue
        })
    }

    changePrice(leftValue, rightValue) {
        let priceText = ''
        if (leftValue == 0 && rightValue == 60) {
            priceText = '不限'
        } else if (leftValue == 0) {
            priceText = rightValue + "万以下"
        } else if (leftValue >= 1 && rightValue == 60) {
            priceText = leftValue + "万以上"
        } else if (leftValue >= 1) {
            priceText = leftValue + "-" + rightValue + "万"
        }

        if(leftValue  == 0){
            leftValue = null
        }
        if(rightValue  == 60){
            rightValue = null
        }

        this.setState({
            priceText: priceText,
            carPriceMin: leftValue,
            carPriceMax: rightValue
        })
    }

    confirmFilter() {
        DeviceEventEmitter.emit('SeekMoreFilterPage', {
            type: 'seekMoreFilter',
            fromPage: this.props.route.params.fromPage,
            mileageMin: this.state.mileageMin,
            mileageMax: this.state.mileageMax,
            mileShowText: this.state.mileShowText,
            registerDateBegin: this.state.registerDateBegin,
            registerDateEnd: this.state.registerDateEnd,
            priceText: this.state.priceText,
            carPriceMin: this.state.carPriceMin,
            carPriceMax: this.state.carPriceMax,
            ageShowText: this.state.ageShowText,
            carOutColor: this.state.carOutColorListData,
            carOutColorPr: this.state.outColors,

            carInColor: this.state.carInColorListData,
            carInColorPr: this.state.inColors
        });
        navigation.goBack()
    }

    resetFilter() {
        this.changeColor(0)
        this.changeInColor(0)
        if (this.rangeSlider && this.rangeSlider.current) {
            this.rangeSlider.current.setLowValue(0);
            this.rangeSlider.current.setHighValue(10);
        }
        if (this.rangeSliderAge && this.rangeSliderAge.current) {
            this.rangeSliderAge.current.setLowValue(0);
            this.rangeSliderAge.current.setHighValue(8);
        }
        if (this.rangeSliderPrice && this.rangeSliderPrice.current) {
            this.rangeSliderPrice.current.setLowValue(0);
            this.rangeSliderPrice.current.setHighValue(60);
        }
    }

}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#f9f9f9',
    },

    bottomTabContainer: {
        width: '100%',
        flexDirection: 'row',
        alignItems: 'flex-start',
        backgroundColor: '#fff'
    },
    resetBtn: {
        flex: 1,
        height: 50,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#f6f6f6'
    },
    confirmBtn: {
        flex: 2,
        height: 50,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#ffde00'
    },
    btnText: {
        fontSize: 16,
        color: '#333333',
        fontWeight: 'bold',
    },
    itemContain: {
        height: 50,
        width: '100%',
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        paddingLeft: 15,
        paddingRight: 15,
        backgroundColor: '#fff'
    },
    titleText: {
        fontSize: 14,
        color: '#333333',
        fontWeight: 'bold',
    },
    mileContain: {
        paddingHorizontal: 15,
        backgroundColor: '#fff',
        marginTop: 1
    },
    mileTitleContain: {
        height: 50,
        width: '100%',
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between'
    },
    mileValueText: {
        fontSize: 14,
        color: '#ff9c00'
    },
    rangeTipContain: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        paddingHorizontal: 5,
        marginBottom: 10
    },

    colorItem: {
        height: 36,
        width: '25%',
        paddingLeft: 15,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'flex-start',
    },
    colorBox: {
        height: 14,
        width: 14,
        marginRight: 5
    },
    colorSelectItem: {
        height: 36,
        width: '25%',
        paddingLeft: 15,
        alignItems: 'center',
        justifyContent: 'flex-start',
        flexDirection: 'row',
        backgroundColor: '#fffadb',
        borderRadius: 4,
        borderWidth: 1,
        borderColor: '#ffde00',

    },
    colorText: {
        fontSize: 12,
        color: '#333333'
    },

    rankItem: {
        height: 32,
        width: '21%',
        flexDirection: 'column',
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: '#ffffff',
        borderRadius: 4,
        borderWidth: 1,
        borderColor: '#d1d1d1',
        marginRight: 15,
        marginBottom: 15
    },
    rankItemSelect: {
        height: 32,
        width: '21%',
        alignItems: 'center',
        justifyContent: 'center',
        flexDirection: 'row',
        backgroundColor: '#fffadb',
        borderRadius: 4,
        borderWidth: 1,
        borderColor: '#ffde00',
        marginRight: 15,
        marginBottom: 15
    }
})